/**
 * 文件名称 : DSMHttpHeadUtil.java
 * <p>
 * 作者信息 : Yang Ke
 * <p>
 * 版权声明 : Copyright (c) 2009-2012 CIeNET Ltd. All rights reserved
 * <p>
 * 文件描述 : DSMHttpHeadUtil.java - DSM HTTP HEAD UTIL
 * <p>
 * 评审记录 :
 * <p>
 */

package com.pactera.utils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.GeneralSecurityException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.X509TrustManager;

import android.util.Log;

/**
 * HTTP连接类
 * 
 * [功能详细描述]
 * @author yujunzhou
 * @version [RCS Client V100R002C03, 2012-5-3]
 */
public class HttpUtil
{
    private static final String TAG = "HttpUtil";
    
    /**
     * 使用TLS协议
     */
    private static final String CLIENT_AGREEMENT = "TLS";
    
    /**
     * 打开URL连接
     * 
     * @param aUrl
     *            要打开的URL连接地址
     * @return URL连接
     */
    public static HttpURLConnection openConnection(String aUrl)
    {
        HttpURLConnection connection = null;
        try
        {
            connection = openConnection(new URL(aUrl));
        }
        catch (Exception e)
        {
            connection = null;
        }
        
        return connection;
    }
    
    /**
     * 打开Https的连接
     * 
     * @param aUrl
     *            要打开的URL连接地址
     * @return Https连接
     */
    public static HttpsURLConnection openHttpsConnection(String aUrl)
    {
        HttpsURLConnection httpsURLConnection = null;
        URL url = null;
        
        try
        {
            url = new URL(aUrl);
            initHttpsConnection();
            httpsURLConnection = (HttpsURLConnection) url.openConnection();
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return null;
        }
        
        return httpsURLConnection;
    }
    
    /**
     * 初始化HttpsConnection
     */
    private static void initHttpsConnection()
    {
        SSLContext sslContext = null;
        
        try
        {
            //取得SSL的SSLContext实例 
            sslContext = SSLContext.getInstance(CLIENT_AGREEMENT);
            X509TrustManager[] xtmArray = new X509TrustManager[] { new X509TrustManager()
            {
                
                public X509Certificate[] getAcceptedIssuers()
                {
                    return null;
                }
                
                public void checkServerTrusted(X509Certificate[] chain,
                        String authType) throws CertificateException
                {
                    
                }
                
                public void checkClientTrusted(X509Certificate[] chain,
                        String authType) throws CertificateException
                {
                    
                }
            } };
            
            //初始化SSLContext  
            sslContext.init(null, xtmArray, new java.security.SecureRandom());
        }
        catch (GeneralSecurityException gse)
        {
            gse.printStackTrace();
        }
        
        if (sslContext != null)
        {
            HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
        }
        
        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier()
        {
            
            public boolean verify(String hostname, SSLSession session)
            {
                //trust any host
                return true;
            }
        });
    }
    
    /**
     * 打开URL连接
     * 
     * @param aUrl
     *            要打开的URL连接地址
     * @return URL连接
     */
    public static HttpURLConnection openConnection(URL aUrl)
    {
        HttpURLConnection connection = null;
        
        //        if (FusionCode.isNeedProxy)
        //        {
        //            // 如果需要代理
        //            Proxy proxy = new Proxy(Proxy.Type.HTTP,
        //                    new InetSocketAddress(FusionCode.HOST_URL,
        //                            Integer.parseInt(FusionCode.HOST_PORT)));
        //            
        //            try
        //            {
        //                connection = (HttpURLConnection) aUrl.openConnection(proxy);
        //            }
        //            catch (IOException e)
        //            {
        //                connection = null;
        //            }
        //        }
        //        else
        //        {
        // 不需要代理
        try
        {
            connection = (HttpURLConnection) aUrl.openConnection();
        }
        catch (IOException e)
        {
            connection = null;
        }
        //        }
        
        return connection;
    }
    
    /**
     * 关闭连接
     * 
     * @param aConnection
     *            HttpURLConnection
     * @param aStream
     *            InputStream
     * @param aOutputStream
     *            aOutputStream
     */
    public static void closeConnection(HttpURLConnection aConnection,
            InputStream aStream, OutputStream aOutputStream)
    {
        if (null != aOutputStream)
        {
            try
            {
                aOutputStream.close();
            }
            catch (IOException e)
            {
                Log.e(TAG, "aOutputStream close error");
            }
        }
        
        if (null != aStream)
        {
            try
            {
                aStream.close();
            }
            catch (IOException e)
            {
                Log.e(TAG, "aStream close error");
            }
        }
        
        if (null != aConnection)
        {
            aConnection.disconnect();
        }
    }
    
    
    /**
	 * 获取HttpURLConnection对象
	 * 
	 * @param urlString
	 * @return
	 * @throws Exception
	 */
	public static HttpURLConnection getHttpURLConnection(String urlString,
			String reqType, String contentType, String contentLength)
			throws Exception {
		HttpURLConnection connection = null;

		URL url = new URL(urlString);
		connection = (HttpURLConnection) url.openConnection();
		connection.setDoInput(true);
		if (reqType.toLowerCase().equals("post")) {
			connection.setDoOutput(true);
		}
		connection.setConnectTimeout(15000);
		connection.setReadTimeout(30000);
		connection.setRequestMethod(reqType);
		connection.setRequestProperty("Content-Type", contentType);
		connection.setRequestProperty("Charset", "utf-8");

		if (contentLength.length() != 0) {
			connection.setRequestProperty("Content-Length", contentLength);
		}
		return connection;
	}

	/**
	 * 获取HttpURLConnection对象有代理
	 * 
	 * @param urlString
	 * @return
	 * @throws Exception
	 */
	public static HttpURLConnection getHttpURLConnection(String urlString,
			String reqType, String contentType, String contentLength,
			String proxyAdd, String proxyPort) throws Exception {
		HttpURLConnection connection = null;
		String urlRelay01 = proxyAdd + ":";
		String urlRelay02 = urlRelay01 + proxyPort;
		String tmp01 = urlString.substring(
				urlString.indexOf("/",
						urlString.indexOf("http://") + "http://".length() + 1),
				urlString.length());
		String urlRelay = urlRelay02 + tmp01;
		String urlProperty = urlString.substring(
				urlString.indexOf("http://") + "http://".length(),
				urlString.indexOf("/",
						urlString.indexOf("http://") + "http://".length()));
		URL url = new URL(urlRelay);
		connection = (HttpURLConnection) url.openConnection();
		connection.setDoInput(true);
		if (reqType.toLowerCase().equals("post")) {
			connection.setDoOutput(true);
		}
		connection.setConnectTimeout(15000);
		connection.setReadTimeout(30000);
		connection.setRequestProperty("X-Online-Host", urlProperty);

		return connection;
	}

}
